<?php

namespace app\tools;

use Yii;
use yii\log\FileTarget;
use app\models\Company;

class Tool
{
    /**
     * @param $message
     * @param string $target
     * @throws \yii\base\InvalidConfigException
     * @throws \yii\log\LogRuntimeException
     */
    public static function log($message, $target = 'app.log'){
        if(is_array($message) or is_object($message)){
            $message = var_export($message, true);
        }

        $log = new FileTarget();
        $log->logFile = Yii::$app->getRuntimePath() . '/logs/'.$target;
        $log->messages[] = [
            $message,
            1,
            'application',
            time()
        ];
        $log->export();
    }

    public static function showPhone($phone) {
        return self::str_replaces($phone, 3, 4);;
    }

    public static function str_replaces($str, $start, $len, $symbol='*') {
        $end = $start + $len;
        // 截取头保留的字符
        $str1 = mb_substr($str, 0, $start);
        // 截取尾保留的字符
        $str2 = mb_substr($str, $end);

        //  生产要替换的字符
        $symbol_num = '';
        for ($i = 0; $i < $len; $i++) {
            $symbol_num .= $symbol;
        }
        return $str1 . $symbol_num . $str2;
    }

    public static function getAccessToken($company_id){
      $redis_key = 'songling_access_token_' . $company_id;
      $redis_value = Yii::$app->redis->get($redis_key);
      if ($redis_value) {
        $access_token = $redis_value;
      } else {
        $company = Company::findOne($company_id);
        $appid = $company->wechat_appid;
        $appsecret = $company->wechat_secret;
        $access_token = '';
        $response = self::curl("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$appid&secret=$appsecret");
        if ($response) {
          $res = json_decode($response, true);
          if($res and isset($res['access_token'])) {
            $access_token = $res['access_token'];
            Yii::$app->redis->set($redis_key, $access_token);
            Yii::$app->redis->expire($redis_key, 5000);
          }
        }
      }
      return $access_token;
    }

    public static function curl($url, $data = []) {
      $curl = curl_init();
      curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'POST');
      curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
      curl_setopt($curl, CURLOPT_TIMEOUT, 3);
      curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
      curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 2);
      curl_setopt($curl, CURLOPT_HEADER, false);
      curl_setopt($curl, CURLOPT_URL, $url);
      if ($data) {
        curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($data,JSON_UNESCAPED_UNICODE));
      }
      $res = curl_exec($curl);
      curl_close($curl);
      return $res;
    }

    public static function getImg($img) {
      $img = str_replace("img.xuanlingyun.com", "img.xuan-ling.cn", $img);
      return $img;
    }
}
